import sys
from PyQt5.QtWidgets import QWidget, QGridLayout, QPushButton,QLabel,QFileDialog,QHBoxLayout,QLineEdit,QCheckBox,QComboBox,QVBoxLayout,QProgressBar,QMessageBox
from PyQt5.QtGui import QPalette,QBrush,QPixmap
from PyQt5 import QtCore,QtGui
import os,work,vars,tools,platform,subprocess


class Main(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        self.resize(650, 550)  # 设置窗体大小
        self.setWindowTitle("优鸥ppt视频生成器")  # 设置窗体标题
        self.show()  # 显示窗体

        self.setContentsMargins(60,100,60,25)
        self.setBG()
        self.UIElements()
        self.checkImageMagick()

    def checkImageMagick(self):
        installed = False
        # 检测环境变量
        system = platform.system()
        if system == 'Linux':
            IMAGEMAGICK_BINARY = os.getenv('IMAGEMAGICK_BINARY', '')
            if len(IMAGEMAGICK_BINARY) == 0:
                p = subprocess.Popen('which convert',
                          stdout=subprocess.PIPE,
                          stderr=None,
                          shell=True
                          )
                p.wait()
                convert_path = p.stdout.read()
                convert_path = convert_path.decode().replace("\n","")
                if len(convert_path) > 0:
                    os.environ['IMAGEMAGICK_BINARY'] = convert_path
                    installed = True
            else:
                installed = True
            if not installed:
                self.message_label.setText("检测到ImageMagick未安装，请在终端运行 sudo apt install imagemagick安装")

    def setBG(self):
        palette = QPalette()
        palette.setBrush(QPalette.Background, QBrush(QPixmap(tools.resource_path("bg.png"))))
        self.setPalette(palette)
        self.setFixedSize(self.width(), self.height())

    def work_background(self):
        vars.gl_filepath = self.filepath.text()
        vars.gl_width = int(self.width_input.text())
        vars.gl_height = int(self.height_input.text())
        vars.gl_need_voice = self.need_voice_checkbox.isChecked()

        vars.gl_voice_type = self.voice_type_combobox.currentIndex()
        vars.gl_need_subtitiles = self.need_subtitles_checkbox.isChecked()
        vars.gl_color = self.color_input.text()

        if vars.gl_voice_type == 0:
            vars.gl_voice_type = 101004 #通用男声
        else:
            vars.gl_voice_type = 101002 #通用女声

        self.workthread = work.workthread()
        self.workthread.resSignal.connect(self.ProgressUpdate)  # 把任务完成的信号与任务完成后处理的槽函数绑定
        self.workthread.start()

    def ProgressUpdate(self, dict):
        result = dict['result']
        if result:
            percent = dict['percent']
            if percent >= 100:
                self.btn.setEnabled(True)
                self.btn.setText('开始生成视频')
                self.message_label.setText("生成结束，视频和pptx文件在同一目录")

            self.progress_bar.setValue(percent)
        else:
            self.progress_bar.setValue(0)
            self.btn.setEnabled(True)
            self.btn.setText('开始生成视频')
            self.message_label.setText("失败：" + dict['message'])
            QMessageBox.information(self, "生成失败", dict['message'], QMessageBox.Yes)

    def do_work(self):
        #判断
        if len(self.filepath.text()) < 2:
            self.message_label.setText("请选择pptx文件")
            return
        if len(self.width_input.text()) < 1:
            self.message_label.setText("请设置视频宽度")
            return
        if int(self.width_input.text()) < 1:
            self.message_label.setText("请设置正确的视频宽度")
            return
        if len(self.height_input.text()) < 2:
            self.message_label.setText("请设置视频高度")
            return
        if int(self.height_input.text()) < 1:
            self.message_label.setText("请设置正确的视频高度")
            return
        if len(self.color_input.text()) != 7 and self.need_subtitles_checkbox.isChecked():
            self.message_label.setText("请设置颜色值，如 #3070EF")
            return
        if not os.path.exists(self.filepath.text()):
            self.message_label.setText("pptx文件未找到，请确保路径正确")
            return

        self.btn.setText('生成中...')
        self.btn.setEnabled(False)
        self.work_background()


    def select_file(self):
        fileName,fileType = QFileDialog.getOpenFileName(self, "选取PPTX文件", os.getcwd(),"PPTX Files(*.pptx)");
        self.filepath.setText(fileName)


    def UIElements(self):
        grid = QGridLayout()

        self.setLayout(grid)

        self.message_label = ClickLabel("请填写下方内容，如需帮助请点我")
        grid.addWidget(self.message_label, 0, 0, 1, 2)

        label1 = QLabel("选择PPTX文件：")
        grid.addWidget(label1, 1, 0)

        hlayout1 = QHBoxLayout()
        vlayout1 = QVBoxLayout()
        self.filepath = QLineEdit()
        selectFileBtn = QPushButton("选择文件")
        selectFileBtn.setProperty("class", "btn btn-light")
        self.filepath.setText("")

        hlayout1.addWidget(self.filepath)
        hlayout1.addWidget(selectFileBtn)
        vlayout1.addLayout(hlayout1)

        label7 = QLabel("pptx中每页的备注会自动转为声音和字幕")
        label7.setProperty("class", "tips-text")

        vlayout1.addWidget(label7)
        vlayout1.setSpacing(0)
        grid.addLayout(vlayout1,1,1)

        label2 = QLabel("视频尺寸（像素）")
        grid.addWidget(label2, 2,0)

        hLayout2 = QHBoxLayout()
        label21 = QLabel("宽")
        label22 = QLabel("高")
        self.width_input = QLineEdit()
        self.height_input = QLineEdit()

        self.width_input.setText("1920")
        self.height_input.setText("1080")

        hLayout2.addWidget(label21)
        hLayout2.addWidget(self.width_input)
        hLayout2.addWidget(label22)
        hLayout2.addWidget(self.height_input)

        grid.addLayout(hLayout2,2,1)

        label3 = QLabel("是否自动配音")
        grid.addWidget(label3, 3,0)
        self.need_voice_checkbox = QCheckBox()
        self.need_voice_checkbox.setChecked(True)
        grid.addWidget(self.need_voice_checkbox, 3,1)

        label4 = QLabel("配音类型")
        grid.addWidget(label4, 4,0)
        self.voice_type_combobox = QComboBox()
        self.voice_type_combobox.addItems(["男声","女声"])
        grid.addWidget(self.voice_type_combobox, 4,1)

        label5 = QLabel("是否需要字幕")
        grid.addWidget(label5, 5,0)
        self.need_subtitles_checkbox = QCheckBox()
        self.need_subtitles_checkbox.setChecked(True)
        grid.addWidget(self.need_subtitles_checkbox, 5,1)

        label6 = QLabel("字幕文字颜色值（RGB）")
        grid.addWidget(label6, 6,0)
        self.color_input = QLineEdit()
        self.color_input.setText("#3070EF")
        grid.addWidget(self.color_input, 6,1)

        #进度条
        self.progress_bar = QProgressBar(self)
        self.progress_bar.setMinimum(0)
        self.progress_bar.setMaximum(100)
        # self.progress_bar.setValue(20)
        grid.addWidget(self.progress_bar,7,0,1,2)

        self.btn = QPushButton('开始生成视频')
        self.btn.setProperty("class", "btn btn-primary")
        grid.addWidget(self.btn, 8,0,1,2)

        self.label80 = ClickLabel("联系我们")
        self.label80.setProperty("class", "tips-text")
        grid.addWidget(self.label80, 9,0,QtCore.Qt.AlignLeft)

        self.label81 = QLabel("生成视频保存在pptx所在的目录")
        self.label81.setProperty("class", "tips-text")
        grid.addWidget(self.label81, 9,1,QtCore.Qt.AlignRight)

        #事件
        self.btn.clicked.connect(self.do_work)
        selectFileBtn.clicked.connect(self.select_file)
        self.need_voice_checkbox.clicked.connect(self.need_voice_changed)
        self.need_subtitles_checkbox.clicked.connect(self.need_subtitles_changed)
        self.label80.clicked.connect(self.contactus)
        self.message_label.clicked.connect(self.help)

    def need_voice_changed(self):
        self.voice_type_combobox.setEnabled(self.need_voice_checkbox.isChecked())

    def need_subtitles_changed(self):
        self.color_input.setEnabled(self.need_subtitles_checkbox.isChecked())
    def contactus(self):
        QtGui.QDesktopServices.openUrl(QtCore.QUrl('https://uopx.cn/ptov#contact-us'))

    def help(self):
        QtGui.QDesktopServices.openUrl(QtCore.QUrl('https://uopx.cn/ptov#help'))

    def closeEvent(self, event):
        if not self.btn.isEnabled():
            reply = QMessageBox.question(self, 'Message',
                                         '任务正在处理，确定要退出吗?', QMessageBox.Yes,
                                         QMessageBox.No)
            if reply == QMessageBox.Yes:
                event.accept()
            else:
                event.ignore()


class ClickLabel(QLabel):
    clicked = QtCore.pyqtSignal()
    def mouseReleaseEvent(self, QMouseEvent):
        if QMouseEvent.button() == QtCore.Qt.LeftButton:
            self.clicked.emit()